<?php

namespace app\admins\controller;

use app\admins\model\Config as ConfigModel;

class Config extends Base
{
    // Curd复用
    use Curd;

    // 初始化
    protected function initialize()
    {
        parent::initialize();
        $this->model = new ConfigModel();
        $this->sort = ['ord' => 'desc', 'id' => 'asc'];
        $this->is_page = true;
        $this->rule = [
            'name|名称' => 'require|alphaDash|token', // 验证token
            'ord|排序' => 'require|integer|max:4',
            'status|状态' => 'require|in:0,1',
        ];

        // 保存时更新时间戳
        if ($this->action === 'save') {
            $this->param['time'] = time();
        }

        // 验证名称唯一
        if (in_array($this->action, ['save', 'save_edit']) && isset($this->param['sid']) && isset($this->param['name'])) {
            $row = $this->model->where([['sid', '=', $this->param['sid']], ['name', '=', $this->param['name']]])->find();
            $this->action === 'save' && $row && $this->errMsg(1, '名称已存在');
            $this->action === 'save_edit' && $row && $row['name'] !== $this->param['name'] && $this->errMsg(1, '名称已存在');
        }

        $this->setting = $this->setting->field('id', 'names')->where('id', '>', 1)->column('names', 'id');
        $this->app->view->assign('setting', $this->setting);
    }

    private function datas($datas)
    {
        $datas = $datas->map(function ($item) {
            // $item['status'] = $item['status'] ? '<span style="color:#c2c2c2">禁用</span>' : '<span style="color:#5FB878">启用</span>';
            $item['stitle'] = $this->setting[$item['sid']];
            $item['time'] = date('Y-m-d H:i:s', $item['time']);
            return $item;
        });
        return $datas;
    }
}
